'use client'

import { useState, useEffect } from 'react'
import { XMarkIcon } from '@heroicons/react/24/outline'

interface User {
  id: number
  name: string
  color: string // 用户颜色用于显示，但不是必须的
}

interface Todo {
  id: number;
  content: string;
  tags: string | null; // Assuming tags are stored as a comma-separated string in DB
  assigned_to: number | null;
  status: string; // and other fields like creator_name, etc.
  // Add other fields from your main Todo interface as needed for pre-filling
}

interface NewTodoModalProps {
  isOpen: boolean
  onClose: () => void
  projectId: number
  currentUserId: number
  currentStatus: string // For new todos, or context for edited ones
  projectMembers: User[]
  onSuccess: (newOrUpdatedTodo: any) => void
  editTodoData?: Todo | null // Optional: Data of the todo being edited
}

export default function NewTodoModal({
  isOpen,
  onClose,
  projectId,
  currentUserId,
  currentStatus,
  projectMembers,
  onSuccess,
  editTodoData, // New prop
}: NewTodoModalProps) {
  const [content, setContent] = useState('')
  const [tags, setTags] = useState('') // Represent tags as a string in the form
  const [assignedTo, setAssignedTo] = useState<number | null>(null)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const isEditMode = Boolean(editTodoData && editTodoData.id);

  useEffect(() => {
    if (isOpen) {
      if (isEditMode && editTodoData) {
        setContent(editTodoData.content || '');
        // Tags from DB might be a comma-separated string or null
        setTags(editTodoData.tags || ''); 
        setAssignedTo(editTodoData.assigned_to || null);
      } else {
        // Reset form for new todo
        setContent('');
        setTags('');
        setAssignedTo(null);
      }
      setError(null);
      setIsSubmitting(false);
    }
  }, [isOpen, editTodoData, isEditMode]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!content.trim()) {
      setError('内容不能为空')
      return
    }
    setIsSubmitting(true)
    setError(null)

    const payload = {
      content,
      tags: tags.split(/[,\s]+/).map(tag => tag.trim()).filter(tag => tag && tag.length > 0),
      // For edit mode, status is NOT sent, as it's handled by drag-and-drop.
      // For create mode, status is currentStatus.
      ...(isEditMode ? {} : { status: currentStatus }), 
      created_by: currentUserId, // This might be ignored by API if it uses session user ID
      project_id: projectId,     // For new todos, and context for existing ones
      assigned_to: assignedTo ? Number(assignedTo) : null,
    };

    try {
      let response;
      if (isEditMode && editTodoData) {
        response = await fetch(`/api/todos/${editTodoData.id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(payload),
        });
      } else {
        response = await fetch('/api/todos', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(payload),
        });
      }

      if (response.ok) {
        const contentType = response.headers.get("content-type");
        if (contentType && contentType.indexOf("application/json") !== -1) {
          const submittedTodo = await response.json();
          // Ensure the status is correctly set for UI update, especially if editing
          // If API doesn't return full todo with status for PUT, merge with original status
          onSuccess({ ...editTodoData, ...submittedTodo, status: editTodoData?.status || submittedTodo.status || currentStatus });
          onClose();
        } else {
          const textResponse = await response.text();
          console.error('API returned non-JSON success response:', textResponse);
          setError(isEditMode ? '更新任务成功，但服务器返回了意外的格式。' : '创建任务成功，但服务器返回了意外的格式。');
        }
      } else {
        const contentType = response.headers.get("content-type");
        let errorDataMessage = `${isEditMode ? '更新' : '创建'}任务失败 (状态码: ${response.status})`;
        if (contentType && contentType.indexOf("application/json") !== -1) {
          const errorData = await response.json();
          errorDataMessage = errorData.message || errorData.error || errorDataMessage;
        } else {
          const errorText = await response.text();
          console.error('API returned non-JSON error response:', errorText);
          if (errorText && errorText.toLowerCase().includes('<!doctype html')) {
             errorDataMessage += '. 服务器返回了一个HTML页面，请检查API接口。';
          } else if (errorText) {
            errorDataMessage = errorText.substring(0, 200);
          }
        }
        setError(errorDataMessage);
      }
    } catch (err) {
      console.error(`Failed to ${isEditMode ? 'update' : 'create'} todo:`, err);
      setError('网络错误，请稍后重试');
    } finally {
      setIsSubmitting(false)
    }
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50 flex justify-center items-center p-4">
      <div className="bg-white p-8 rounded-lg shadow-xl w-full max-w-md relative">
        <button
          onClick={onClose}
          className="absolute top-4 right-4 text-gray-400 hover:text-gray-600"
        >
          <XMarkIcon className="h-6 w-6" />
        </button>
        <h2 className="text-2xl font-semibold mb-6 text-gray-800">
          {isEditMode ? `编辑任务` : `创建新任务 - ${currentStatus}`}
        </h2>
        
        <form onSubmit={handleSubmit} className="space-y-6">
          <div>
            <label htmlFor="content" className="block text-sm font-medium text-gray-700 mb-1">
              任务内容 <span className="text-red-500">*</span>
            </label>
            <textarea
              id="content"
              value={content}
              onChange={(e) => setContent(e.target.value)}
              rows={4}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm p-2"
              required
            />
          </div>

          <div>
            <label htmlFor="tags" className="block text-sm font-medium text-gray-700 mb-1">
              标签 (逗号或空格分隔)
            </label>
            <input
              type="text"
              id="tags"
              value={tags}
              onChange={(e) => setTags(e.target.value)}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm p-2"
              placeholder="例如: 重要 紧急, 高优先级"
            />
          </div>

          <div>
            <label htmlFor="assignedTo" className="block text-sm font-medium text-gray-700 mb-1">
              分配给
            </label>
            <select
              id="assignedTo"
              value={assignedTo === null ? '' : assignedTo.toString()}
              onChange={(e) => setAssignedTo(e.target.value ? Number(e.target.value) : null)}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm p-2 bg-white"
            >
              <option value="">未分配</option>
              {projectMembers.map((member) => (
                <option key={member.id} value={member.id.toString()}>
                  {member.name}
                </option>
              ))}
            </select>
          </div>

          {error && (
            <p className="text-sm text-red-600 bg-red-50 p-3 rounded-md">{error}</p>
          )}

          <div className="flex justify-end space-x-3 pt-2">
            <button
              type="button"
              onClick={onClose}
              disabled={isSubmitting}
              className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
            >
              取消
            </button>
            <button
              type="submit"
              disabled={isSubmitting}
              className="px-4 py-2 text-sm font-medium text-white bg-indigo-600 border border-transparent rounded-md shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50 disabled:bg-indigo-400"
            >
              {isSubmitting ? (isEditMode ? '保存中...' : '创建中...') : (isEditMode ? '保存更改' : '创建任务')}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
} 